import './index.scss'

import { Dropdown } from 'antd'
import { useState } from 'react'
import { useRequest } from 'alova'
import { useEventEmitter, useMount, useReactive } from 'ahooks'

import { PivotEngine } from '@grapecity/wijmo.olap';
import { PivotGrid } from '@grapecity/wijmo.react.olap';
import { FlexGridFilter } from "@grapecity/wijmo.react.grid.filter"
import { GroupPanel } from "@grapecity/wijmo.react.grid.grouppanel"
import { Row, DataMap, GroupRow, CellRange } from '@grapecity/wijmo.grid'
import { CollectionView, SortDescription, saveFile, Globalize } from '@grapecity/wijmo'
import { FlexGrid, FlexGridColumn, FlexGridCellTemplate } from '@grapecity/wijmo.react.grid'
import { MultiRow, MultiRowCell, MultiRowCellGroup, MultiRowCellTemplate } from '@grapecity/wijmo.react.grid.multirow'


import { Http } from '../Api'
import { ModelBox, DrawerBox } from '../Model'
import { objectArrValue } from '../Utils/configFun'

export const getBaseData = (num) => {
    const randBetween = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
    const pickOne = (items) => items[randBetween(0, items.length - 1)];
    const mapping = '0,1,2,3,4'.split(',')
    const data = [...Array(num)].map((_, i) => ({
        uuid: i + 1,
        country: pickOne(mapping),
        product: pickOne(mapping),
        date: new Date(2014, i % 12, i % 28),
        discount: Math.random() * .3,
        downloads: Math.round(Math.random() * 200000),
        sales: Math.random() * 100000,
        expenses: Math.random() * 50000,
        num01: Math.random() * 5000,
        num02: Math.random() * 5000,
        num03: Math.random() * 5000,
        num04: Math.random() * 5000,
        num05: Math.random() * 5000,
        num06: Math.random() * 5000,
        state: pickOne(mapping)
    }))
    return data
}
export const getDataTree = [
    {
        name: '张三',
        checks: [
            {
                name: '上午',
                earnings: [
                    { name: 'hourly', hours: 30.0, rate: 15.0 },
                    { name: 'overtime', hours: 10.0, rate: 20.0 },
                    { name: 'bonus', hours: 5.0, rate: 30.0 }
                ]
            },
            {
                name: '下午',
                earnings: [
                    { name: 'hourly', hours: 20.0, rate: 18.0 },
                    { name: 'overtime', hours: 20.0, rate: 24.0 }
                ]
            }
        ]
    },
    {
        name: '李四',
        checks: [
            {
                name: '上午',
                earnings: [
                    { name: 'hourly', hours: 30.0, rate: 15.0 },
                    { name: 'overtime', hours: 10.0, rate: 20.0 },
                    { name: 'bonus', hours: 5.0, rate: 30.0 }
                ]
            },
            {
                name: '下午',
                earnings: [
                    { name: 'hourly', hours: 20.0, rate: 18.0 },
                    { name: 'overtime', hours: 20.0, rate: 24.0 }
                ]
            }
        ]
    },
    {
        name: '王二麻子',
        checks: [
            {
                name: '上午',
                earnings: [
                    { name: 'hourly', hours: 30.0, rate: 15.0 },
                    { name: 'overtime', hours: 10.0, rate: 20.0 },
                    { name: 'bonus', hours: 5.0, rate: 30.0 }
                ]
            },
            {
                name: '下午',
                earnings: [
                    { name: 'hourly', hours: 20.0, rate: 18.0 },
                    { name: 'overtime', hours: 20.0, rate: 24.0 }
                ]
            }
        ]
    }
]

export const OlapData = (num) => {
    const randBetween = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
    const products = [
        { product: 'Wijmo', platform: 'Web' },
        { product: 'ActiveReports', platform: 'Desktop' },
        { product: 'ActiveReportsJS', platform: 'Web' },
        { product: 'ComponentOne', platform: 'Desktop' },
        { product: 'Spread', platform: 'Desktop' },
        { product: 'SpreadJS', platform: 'Web' },
        { product: 'GCDocs', platform: 'Desktop' }
    ]
    const agents = [
        { agent: 'Ashlyn Dunlop', region: 'East' },
        { agent: 'Keith Vang', region: 'East' },
        { agent: 'Bobbi Rodrigues', region: 'West' },
        { agent: 'Charli Medina', region: 'West' },
        { agent: 'Kaitlin Salt', region: 'West' },
    ]
    const year = new Date().getFullYear()
    const data = [...Array(num)].map((_, i) => {
        const productIndex = randBetween(0, 6);
        const agentIndex = randBetween(0, 4);
        return {
            id: i + 1,
            platform: products[productIndex].platform,
            product: products[productIndex].product,
            agent: agents[agentIndex].agent,
            region: agents[agentIndex].region,
            date: new Date(year - randBetween(0, 2), randBetween(0, 11), randBetween(0, 27)),
            sales: randBetween(1500, 3500),
            downloads: randBetween(10, 200),
            revenue: randBetween(500, 1000)
        }
    })
    return data
}


// 普通表格组件
export const WijmoClassBase = ({ templateData }) => {
    // console.log('模板参数', templateData)
    const { url, configuration, initParameter, columns, optionsBtn } = templateData
    const { abc, groupPanel, addTop, addBtm, addSum, addIndex, topText, btmText, group, sort, filter } = initParameter
    const InitWijmo = useReactive({ init: null })
    const { send } = useRequest(params => Http({ url: 'getTextData', params }), { immediate: false })
    const [Data, setData] = useState([])
    const [OptionsCall, setOptionsCall] = useState()

    const init = (e) => {
        const params = {
            tenderGuid: '82CC28BC-861B-44E0-8B00-3C9A649A849C',
            pageSize: 1000,
            pageIndex: 1,
            fieldOrder: 'meterageCode'
        }
        // send(params).then(res => {
        //     InitWijmo.init = e
        //     // 初始化数据 默认序列化
        //     // 测试用数据加载
        //     // const resData = typeof (url) === 'number' ? getBaseData(url) : getDataTree
        //     const data = new CollectionView(res.data, { groupDescriptions: group, sortDescriptions: sort })
        //     console.log(data)
        //     // 初始化数据处理
        //     if (abc) console.error('不存在的函数-报错测试')
        //     if (addTop) e.columnHeaders.rows.push(new Row())
        //     if (addBtm || addSum) e.columnFooters.rows.push(addSum ? new GroupRow() : new Row())
        //     setData(data)
        // })
        InitWijmo.init = e
        // 初始化数据 默认序列化
        // 测试用数据加载
        const resData = typeof (url) === 'number' ? getBaseData(url) : getDataTree
        const data = new CollectionView(resData, { groupDescriptions: group, sortDescriptions: sort })
        // 初始化数据处理
        if (abc) console.error('不存在的函数-报错测试')
        if (addTop) e.columnHeaders.rows.push(new Row())
        if (addBtm || addSum) e.columnFooters.rows.push(addSum ? new GroupRow() : new Row())
        setData(data)
    }

    const onRefresh = () => init(InitWijmo.init)
    const onAdded = () => setOptionsCall({ type: 'Added', title: '新增数据', data: columns })
    const onDelete = () => setOptionsCall({ type: 'Delete', title: '删除警告!', data: Data.currentItem, width: 600 })
    const onModify = () => setOptionsCall({ type: 'Modify', title: '修改数据', data: { columns, item: Data.currentItem } })
    const onSaveAct = () => saveFile(InitWijmo.init.getClipString(null, true, true), '选中数据.csv')
    const onSaveAll = () => {
        const rng = new CellRange(0, 0, InitWijmo.init.rows.length - 1, InitWijmo.init.columns.length - 1)
        saveFile(InitWijmo.init.getClipString(rng, true, true), '全部数据.csv')
    }

    const OptionsConfig = (e) => {
        const eventHandlers = {
            onRefresh,
            onAdded,
            onDelete,
            onModify,
            onSaveAct,
            onSaveAll,
        };
        const handler = eventHandlers[e]
        if (handler) handler()
        else console.error(`未找到事件 '${e}' 的处理程序`);
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { data, type } = val
        const { init } = InitWijmo
        if (type === 'Delete') init.collectionView.remove(data)
        if (type === 'Added') init.collectionView.addNew(data)
        if (type === 'Modify') {
            init.collectionView.editItem(Data.currentItem)
            Object.keys(Data.currentItem).forEach(key => Data.currentItem[key] = data[key])
            init.collectionView.commitEdit()
        }
    })

    const getDataMap = (e) => {
        const data = Object.keys(e).map((key) => ({ value: key, label: e[key].text || e[key] }))
        return new DataMap(data, 'value', 'label')
    }
    const CustonGroup = (e) => {
        if (e.col.aggregate !== 0) {
            const { aggTitle, format } = objectArrValue(columns, e.col.binding, 'dataIndex')
            return `${aggTitle} : ${Globalize.formatNumber(e.value, format)}`
        }
    }

    return (
        <div className='WijmoClass WijmoClassBase'>
            {groupPanel && <GroupPanel className="GroupPanel" grid={InitWijmo.init} placeholder="将列拖动到此处以创建组(最多6组)" />}
            <Dropdown menu={{ items: optionsBtn(OptionsConfig) }} trigger={['contextMenu']}>
                <div>
                    <FlexGrid
                        itemsSource={Data}
                        initialized={init}
                        {...configuration}
                    >
                        <FlexGridCellTemplate cellType="TopLeft" template={() => topText} />
                        {(addBtm || addSum) && <FlexGridCellTemplate cellType="BottomLeft" template={() => btmText} />}
                        <FlexGridCellTemplate cellType="RowHeader" template={e => addIndex ? e.row.index + 1 : ''} />
                        {filter && <FlexGridFilter />}
                        {columns.map(({ dataIndex, title, valueEnum, valueType, ...config }) => {
                            if (valueType === 'Hidden') return false
                            return (
                                <FlexGridColumn key={dataIndex} header={title} binding={dataIndex} dataMap={getDataMap(valueEnum || '')} {...config}>
                                    <FlexGridCellTemplate cellType="Group" template={CustonGroup} />
                                    <FlexGridCellTemplate cellType="ColumnFooter" template={CustonGroup} />
                                </FlexGridColumn>
                            )
                        })}
                    </FlexGrid>
                </div>
            </Dropdown>
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div >
    )
}
// 复合头部组件
export const WijmoClassMultiRow = ({ templateData }) => {
    // console.log('[复合组件基础配置]', templateData)
    const { url, configuration, initParameter, layout, columns, optionsBtn } = templateData
    const { addIndex, topText, btmText, group, sort, filter } = initParameter
    const InitWijmo = useReactive({ init: null })
    const [Data, setData] = useState()
    const [OptionsCall, setOptionsCall] = useState()

    const init = (e) => {
        InitWijmo.init = e
        const data = new CollectionView(getBaseData(url), { groupDescriptions: group, sortDescriptions: sort })
        setData(data)
    }



    const onRefresh = () => init(InitWijmo.init)
    const onAdded = () => setOptionsCall({ type: 'Added', title: '新增数据', data: columns })
    const onDelete = () => setOptionsCall({ type: 'Delete', title: '删除警告!', data: Data.currentItem, width: 600 })
    const onModify = () => setOptionsCall({ type: 'Modify', title: '修改数据', data: { columns, item: Data.currentItem } })
    const onSaveAct = () => saveFile(InitWijmo.init.getClipString(null, true, true), '选中数据.csv')
    const onSaveAll = () => {
        const rng = new CellRange(0, 0, InitWijmo.init.rows.length - 1, InitWijmo.init.columns.length - 1)
        saveFile(InitWijmo.init.getClipString(rng, true, true), '全部数据.csv')
    }
    const OptionsConfig = (e) => {
        const eventHandlers = {
            onRefresh,
            onAdded,
            onDelete,
            onModify,
            onSaveAct,
            onSaveAll,
        };
        const handler = eventHandlers[e]
        if (handler) handler()
        else console.error(`未找到事件 '${e}' 的处理程序`);
    }
    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { data, type } = val
        const { init } = InitWijmo
        if (type === 'Delete') init.collectionView.remove(data)
        if (type === 'Added') init.collectionView.addNew(data)
        if (type === 'Modify') {
            init.collectionView.editItem(Data.currentItem)
            Object.keys(Data.currentItem).forEach(key => Data.currentItem[key] = data[key])
            init.collectionView.commitEdit()
        }
    })

    const getDataMap = (e) => {
        const { valueEnum } = objectArrValue(columns, e, 'dataIndex')
        if (valueEnum) {
            const data = Object.keys(valueEnum).map((key) => ({ value: key, label: valueEnum[key].text || valueEnum[key] }))
            return new DataMap(data, 'value', 'label')
        }
    }
    const CustonGroup = (e) => {
        if (e.col.aggregate !== 0) {
            const { aggTitle, format } = objectArrValue(columns, e.col.binding, 'dataIndex')
            return `${aggTitle} : ${Globalize.formatNumber(e.value, format)}`
        }
    }

    return (
        <div className='WijmoClass WijmoClassMultiRow'>
            <Dropdown menu={{ items: optionsBtn(OptionsConfig) }} trigger={['contextMenu']}>
                <div>
                    <MultiRow
                        itemsSource={Data}
                        initialized={init}
                        {...configuration}
                    >
                        <MultiRowCellTemplate cellType="TopLeft" template={topText ? () => topText : null} />
                        <MultiRowCellTemplate cellType="RowHeader"
                            template={addIndex ? (e) => e.row.index / e.row.grid.rowsPerItem + 1 : null}
                        />
                        {filter && <FlexGridFilter />}
                        {layout.map((item, index) => {
                            const { header, colspan, align, cells, width } = item
                            return (
                                <MultiRowCellGroup key={index} header={header} colspan={colspan} align={align}>
                                    {cells.map(({ binding, title, ...config }) => (
                                        <MultiRowCell
                                            key={`${index}-${binding}`}
                                            binding={binding}
                                            header={title}
                                            {...config}
                                            dataMap={getDataMap(binding)}
                                        >
                                            <MultiRowCellTemplate cellType="Group" template={CustonGroup} />
                                        </MultiRowCell>
                                    ))}
                                </MultiRowCellGroup>
                            )
                        })}
                    </MultiRow>
                </div>
            </Dropdown>
            <ModelBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}
// 数据枢纽组件
export const WijmoClassOLAP = ({ templateData }) => {
    const { url, configuration, initParameter, optionsBtn, gridConfig } = templateData


    const [OptionsCall, setOptionsCall] = useState()
    const [SwitchGrouping, setSwitchGrouping] = useState('1-3')
    const InitWijmo = useReactive({ init: null })
    const init = (init) => {
        InitWijmo.init = init
        const data = getBaseData(url)
        InitWijmo.Data = new PivotEngine({ itemsSource: data, ...initParameter })
    }

    const onRefresh = () => init(InitWijmo.init)
    const onSaveAct = () => saveFile(InitWijmo.init.getClipString(null, true, true), '选中数据.csv')
    const onSaveAll = () => {
        const rng = new CellRange(0, 0, InitWijmo.init.rows.length - 1, InitWijmo.init.columns.length - 1)
        saveFile(InitWijmo.init.getClipString(rng, true, true), '全部数据.csv')
    }

    const onRawData = () => {
        setOptionsCall({
            type: 'WijmoFlexGrid',
            title: '原始数据',
            width: '95vw',
            data: { itemsSource: InitWijmo.Data, gridConfig },
        })
    }
    const onConsole = () => {
        setOptionsCall({
            type: 'WijmoPivotPanel',
            title: '数据控制台',
            placement: 'left',
            width: 800,
            data: { itemsSource: InitWijmo.Data, sheet: 'xxxx', menuSelect: SwitchGrouping },
        })
    }

    const onSearch = () => {
        console.log('条件搜索')
    }

    const onChart = () => {
        setOptionsCall({
            type: 'WijmoPivotChart',
            title: '数据图例',
            width: '90vw',
            data: { itemsSource: InitWijmo.Data },
        })


    }

    const OptionsConfig = (e) => {
        const eventHandlers = {
            onRefresh,
            onSaveAct,
            onSaveAll,
            onRawData,
            onConsole,
            onSearch,
            onChart,
        };
        const handler = eventHandlers[e]
        if (handler) handler()
        else console.log(`未找到事件 '${e}' 的处理程序`);
    }

    const ModalEvent = useEventEmitter()
    ModalEvent.useSubscription(val => {
        const { type, data } = val
        if (type === 'SwitchGrouping') {
            // setSwitchGrouping(data)
            setSwitchGrouping(data.menuSelect)
            InitWijmo.Data.viewDefinition = JSON.stringify(data.viewDefinition)
        }
    })

    return (
        <div className='WijmoClass WijmoClassOLAP'>
            <Dropdown menu={{ items: optionsBtn(OptionsConfig) }} trigger={['contextMenu']}>
                <div>
                    <PivotGrid
                        initialized={init}
                        itemsSource={InitWijmo.Data}
                        {...configuration}
                    />
                </div>
            </Dropdown>
            <DrawerBox OptionsCall={OptionsCall} ModalEvent={ModalEvent} />
        </div>
    )
}